package org.lalib.util;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Hex;
import org.lalib.controller.service.CHistoricalValueService;
import org.lalib.controller.service.CVariableService;
import org.lalib.entity.object.variable.EVariable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("passwordUtil")
public class PasswordUtil {

	@Autowired
	private CHistoricalValueService cHistoricalValueService;

	@Autowired
	private CVariableService cVariableService;

	public String hash(String value) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		messageDigest.reset();
		messageDigest.update(value.getBytes(Charset.forName("UTF8")));
		final byte[] resultByte = messageDigest.digest();
		String result = new String(Hex.encodeHex(resultByte));
		return result;
	}

	public boolean isUsernameUnique(String username) {
		EVariable usernameVariable = cVariableService.getVariableByName("password");
		return cHistoricalValueService.getValues(usernameVariable, username).size() < 2;
	}
}